(function () {
    function postParentMessage(type, data) {
        window.parent.postMessage(
            {
                origin: "localInspector",
                type: type,
                data: data
            },
            "*"
        );
    }

    function addElementClasss(className, newClassName) {
        var elements = document.querySelectorAll(className);
        if (elements.length) {
            elements.forEach(function (element) {
                element.classList.add(className, newClassName);
            });
        }
    }

    function removeElementClasss(className, hideClassName) {
        var elements = document.querySelectorAll(className);
        if (elements.length) {
            elements.forEach(function (element) {
                element.classList.remove(hideClassName);
            });
        }
    }

    function createHoverElement() {
        const div = document.createElement("div");
        div.id = "app-hover-element";
        div.style.cssText = "position: absolute;pointer-events: none;border: 2px dashed red;box-sizing: border-box;z-index:19999";
        document.body.append(div);
    }
    
    function addEventListenerAllHover() {
        if (document.getElementById("app-hover-element")) {
            return;
        }
        createHoverElement();
        let currentElement;
        var bodyElement = document.querySelector("body");
        
        var elements = bodyElement.querySelectorAll("*");
        
        elements.forEach(function (element) {
            element.addEventListener("mousemove", function (event) {
                event.stopPropagation();
                event.preventDefault();
                if (window["LEDITOR_STATUS"] === false) {
                    return false;
                }
                const target = event.target;
                if (currentElement !== target && !["app-hover-element"].includes(target.className)) {
                    currentElement = target;
                    setElementPosition(target, "app-hover-element");

                    
                    
                    
                }
            });

            
            
            
            
            
            
            
        });
        
        
        
        
        
        
        
        
        
        
    }

    function aPreventDefault() {
        
        var links = document.getElementsByTagName("a");
        
        for (var i = 0; i < links.length; i++) {
            links[i].addEventListener("click", function (event) {
                if (window["LEDITOR_STATUS"] === false) {
                    return false;
                }
                event.preventDefault(); 
            });
        }
    }

    function getNodeIndex(currentNode) {
        
        
        
        
        
        var siblings = Array.from(currentNode.parentNode.children);
        var index = siblings.indexOf(currentNode);
        return index + 1;
    }

    function getParentElementId(selectedElement) {
        
        
        
        const parentTag = [];

        
        var parentElement = selectedElement.parentElement;

        
        while (parentElement && parentElement.id === "") {
            let tagName = parentElement.tagName.toLowerCase();
            const nodeIndex = getNodeIndex(parentElement);
            if (nodeIndex) {
                tagName += `:nth-child(${nodeIndex})`;
            }
            parentTag.unshift(tagName);

            parentElement = parentElement.parentElement;
        }

        if (parentElement) {
            parentTag.unshift("#" + parentElement.id);
        }

        return parentTag.join(">");
    }

    function getTargetClass(target, isAll) {
        let clsName = target.className;
        if (typeof clsName != "string") {
            clsName = "";
        }
        const classNames = clsName.split(" ").filter((el) => el);
        const classList = classNames.length ? classNames.map((el) => "." + el) : [target.tagName.toLowerCase()];
        if (isAll) {
            return classList.filter((el) => el).join("");
        } else {
            if (target.id) {
                return `#${target.id}`;
            }
            const nodeIndex = getNodeIndex(target);
            var parentID = getParentElementId(target);
            return `${parentID} ${classList[0]}:nth-child(${nodeIndex})`;
        }
    }

    function setTargetSelectID(target) {
        const sectionID = target.getAttribute("section-id");
        if (!sectionID) {
            target.setAttribute("section-id", new Date().getTime());
        }
    }

    function getTargetSelectID(target) {
        return target.getAttribute("section-id");
    }

    function createClickElement() {
        const div = document.createElement("div");
        div.id = "app-click-element";
        div.style.cssText = "position: absolute;pointer-events: none;border: 2px solid red;box-sizing: border-box;z-index:9999";
        document.body.append(div);
    }

    function setElementPosition(target, id) {
        const height = target.clientHeight || target.offsetHeight;
        const width = target.clientWidth || target.offsetWidth;
        const top = target.getBoundingClientRect().top + (document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop);
        const left = target.getBoundingClientRect().left;
        const clickDiv = document.getElementById(id);
        clickDiv.style.top = top + "px";
        clickDiv.style.left = left + "px";
        clickDiv.style.width = width + "px";
        clickDiv.style.height = height + "px";
    }

    function addEventListenerAllClick(callback) {
        if (document.getElementById("app-click-element")) {
            return;
        }
        createClickElement();
        var bodyElement = document.querySelector("body");
        
        var elements = bodyElement.querySelectorAll("*");

        let clickCount = 0;
        let timer;
        function handleClick(event) {
            if (window["LEDITOR_STATUS"] === false) {
                return false;
            }
            event.stopPropagation();
            event.preventDefault();
            const target = event.target;
            clickCount++;

            if (clickCount === 1) {
                setElementPosition(target, "app-click-element");
                setTargetSelectID(target);
                postParentMessage("selectTarget", {
                    id: getTargetSelectID(target),
                    tagName: target.tagName,
                    targetClass: getTargetClass(target, true),
                    targetId: getTargetClass(target, false)
                });
                timer = setTimeout(() => {
                    clickCount = 0; 
                }, 300);
            } else if (clickCount === 2) {
                clearTimeout(timer);
                const parentElement = target.parentNode;
                setElementPosition(parentElement, "app-click-element");
                postParentMessage("selectTarget", {
                    id: getTargetSelectID(parentElement),
                    targetClass: getTargetClass(parentElement, true),
                    targetId: getTargetClass(parentElement, false)
                });
                clickCount = 0; 
            }
        }

        
        elements.forEach(function (element) {
            element.addEventListener("click", handleClick);
        });
    }

    function appendStyle(id, content) {
        var existingStyle = document.getElementById(id);

        if (existingStyle) {
            
            existingStyle.textContent = content;
        } else {
            
            var style = document.createElement("style");
            style.setAttribute("id", id);
            style.textContent = content;
            document.head.appendChild(style);
        }
    }

    var localInspectorEvent = {
        
        elementFocus(data) {
            window["LEDITOR_STATUS"] = true;
            addEventListenerAllHover();
            addEventListenerAllClick();
            aPreventDefault();
        },
        openPageEdit(data) {
            var hover = document.getElementById("app-hover-element");
            var click = document.getElementById("app-click-element");
            if (click) {
                click.style.display = "block";
            }

            if (hover) {
                hover.style.display = "block";
            }
            window["LEDITOR_STATUS"] = true;
        },
        closePageEdit(data) {
            var hover = document.getElementById("app-hover-element");
            var click = document.getElementById("app-click-element");
            if (click) {
                click.style.display = "none";
            }

            if (hover) {
                hover.style.display = "none";
            }
            window["LEDITOR_STATUS"] = false;
        },
        setElementStyle(data) {
            appendStyle(data.id, data.content);
            setElementPosition($(`[section-id=${data.id}]`)[0], "app-click-element");
        },

        selectElement(data) {
            if (data.id) {
                setElementPosition($(`[section-id=${data.id}]`)[0], "app-click-element");
                $("html,body")
                    .stop()
                    .animate({ scrollTop: $(`[section-id=${data.id}]`).offset().top - 100 }, 400, "linear");
            }
        },

        
        getWindowInfo(data) {
            var windowVal = window[data.key];
            postParentMessage("getWindowInfo", windowVal);
        },
        
        getWindowDatas(data) {
            if (data.keys) {
                var windowVals = data.keys.map((key) => window[key]);
                postParentMessage("getWindowDatas", windowVals);
            }
        },
        
        getAppDatas(data) {
            var appData = [];

            Object.keys(window).forEach((key) => {
                if (key.indexOf("app") != -1) {
                    appData.push(key);
                }
            });
            postParentMessage("getAppDatas", appData);
        }
    };


    window.addEventListener("message", function (e) {
        var messageData = JSON.parse(JSON.stringify(e.data));
        
        if (messageData && messageData.origin && messageData.origin === "localInspector") {
            localInspectorEvent[messageData.type] && localInspectorEvent[messageData.type](messageData.data);
            return "";
        }
    });


    
})();
document.addEventListener("DOMContentLoaded",function(){
    if(moi.getUrlParam("is_theme_edit") === '1'){
        moi.setCookie("is_theme_edit",'1','d2')
    } 
})

